package com.aidong.chat.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.factory.annotation.Autowired;

import com.aidong.chat.biz.ChatLogBiz;
import com.aidong.chat.entity.ChatLogEntity;
import com.aidong.util.CalendarUtil;
import com.aidong.util.PageUtil;
import com.aidong.util.ReadPropertiesUtil;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 私信聊天action
 * @author user
 *
 */
@ParentPackage("json")
@Namespace("/")
public class ChatLogAction implements ModelDriven<ChatLogEntity> {
	
	private ChatLogEntity chatLog;
	
	@Override
	public ChatLogEntity getModel() {
		if(chatLog == null){
			chatLog = new ChatLogEntity();
		}
		return chatLog;
	}
	
	private ChatLogBiz chatLogBiz;
	
	@Autowired
	public void setChatLogBiz(ChatLogBiz chatLogBiz) {
		this.chatLogBiz = chatLogBiz;
	}

	private Map<String, Object> map;
	
	@JSON
	public Map<String, Object> getMap() {
		return map;
	}
	
	/**
	 * 新增聊天记录
	 * @return
	 */
	@Action(value="sendmessage",results={@Result(name="succ",type="json",params={"root","map"})})
	public String insertGround(){
		map = new HashMap<String, Object>();
		
		Date date = new Date(); // 得到当前系统时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd/ HH:mm:ss");
        String time = format.format(date);
        
        chatLog.setDateTime(time); // 设置发送时间
		
		try {
			chatLogBiz.addMessage(chatLog);
		} catch (Exception e) {
			 e.printStackTrace();
			map.put("code", 0);
			map.put("msg", "系统异常");
			return "succ";
		}
		map.put("code", 1);
		map.put("msg", "发送成功"); 
		return "succ";
	}
	
	/**
	 * 查看聊天记录
	 * @return
	 */
	@Action(value="initmessage",results={@Result(name="succ",type="json",params={"root","map"})})
	public String getInitMessage(){
		Map<String, Object> pageMap = PageUtil.page(100, chatLog.getPageCurrent());
		pageMap.put("sender", chatLog.getSender()); // 发送人
		pageMap.put("recipient", chatLog.getRecipient()); // 接收人
		List<ChatLogEntity> chatLog = chatLogBiz.getInitMessage(pageMap);
		Collections.sort(chatLog);
		map = new HashMap<String, Object>();
		
		List<Map<String, Object>> chats = new ArrayList<Map<String,Object>>();
		for (ChatLogEntity chat : chatLog) {
			Map<String, Object> recodeMap = new HashMap<String, Object>();
			recodeMap.put("infoId", chat.getCid());
			recodeMap.put("content", chat.getContent());
			recodeMap.put("dateTime", chat.getDateTime());
			String headUrl = chat.getHeadUrl();
			if(!"".equals(headUrl) && null != headUrl){
				recodeMap.put("headUrl", ReadPropertiesUtil.getIMGREAD(chat.getHeadUrl()+""));
			}
			recodeMap.put("recipient", chat.getRecipient());
			recodeMap.put("sender", chat.getSender());
			recodeMap.put("otherNickName", chat.getOtherNickName());
			String otherUrl = chat.getHeadUrl();
			if(!"".equals(otherUrl) && null != otherUrl){
				recodeMap.put("otherHeadUrl", ReadPropertiesUtil.getIMGREAD(chat.getOtherHeadUrl()+""));
			}
			chats.add(recodeMap);
		}
		
		map.put("chats", chats);
		map.put("pageCurrent", pageMap.get("pageCurrent"));
		return "succ";
	}
	
	/**
	 * 消息列表
	 * @return
	 * @throws Exception 
	 */
	@Action(value="messagelist",results={@Result(name="succ",type="json",params={"root","map"})})
	public String getMessageList() {
		map = new HashMap<String, Object>();
		int sender = chatLog.getSender(); // 客户端用户名
		try {
			List<ChatLogEntity> chats = chatLogBiz.getMessageList(sender); // 获得消息列表
			
			if(chats.size() == 0){
				map.put("code", 0);
				map.put("msg", "没有聊天伙伴");
				return "succ";
			}
			HashMap<Integer, Integer> pair = new HashMap<Integer, Integer>();

			List<Integer> recipients = new ArrayList<Integer>();
			
			HashMap<Integer, ChatLogEntity> userInfoMap = new HashMap<Integer, ChatLogEntity>();
			
			List<Map<String, Object>> resultMap = new ArrayList<Map<String,Object>>();
			
			Map<String, Object> messageMap=null;
			int recipient;
			
			for (ChatLogEntity chatLogs : chats) {
				int count = chatLogs.getSender() + chatLogs.getRecipient();
				int cid = chatLogs.getCid();
				if (!pair.containsKey(count)) {
					pair.put(count, chatLogs.getCid());
				} else {
					cid = pair.get(count) > chatLogs.getCid() ? pair.get(count)
							: chatLogs.getCid();
					pair.put(count, cid);
				}
				
				if (chatLogs.getSender() == sender) { // 如过发件人是自己，就取收件人的id
					recipient=chatLogs.getRecipient();
				} else { // 如过收件人是自己，就取发件人的id
					recipient=chatLogs.getSender();
				}
				if (!recipients.contains(Integer.valueOf(recipient))) {
					recipients.add(recipient);
				}
			}
			map = new HashMap<String, Object>();
			List<Integer> list = new ArrayList<Integer>(pair.values());
			map.put("list", list);
			List<ChatLogEntity> messages = chatLogBiz.getMessageListByIds(map);

			map.put("repiList", recipients);
			List<ChatLogEntity> userInfo = chatLogBiz.getUserInfo(map);

			for (ChatLogEntity info : userInfo) {
				userInfoMap.put(info.getIdongId(),info);
			}
			for (ChatLogEntity chatLogs : chats) {
				if (chatLogs.getCid()
						- pair.get(chatLogs.getSender() + chatLogs.getRecipient()) == 0) {
					ChatLogEntity chatLogEntity = new ChatLogEntity();
					if (chatLogs.getSender() == sender) { // 如过发件人是自己，就取收件人的id
						chatLogEntity.setOppositer(chatLogs.getRecipient());
						chatLogEntity.setNickName(userInfoMap.get(
								chatLogs.getRecipient()).getNickName());
						chatLogEntity.setHeadUrl(userInfoMap.get(
								chatLogs.getRecipient()).getHeadUrl());
					}

					if (chatLogs.getRecipient() == sender) { // 如过收件人是自己，就取发件人的id
						chatLogEntity.setOppositer(chatLogs.getSender());
						chatLogEntity.setNickName(userInfoMap.get(
								chatLogs.getSender()).getNickName());
						chatLogEntity.setHeadUrl(userInfoMap.get(
								chatLogs.getSender()).getHeadUrl());
					}

					//新版
					for (ChatLogEntity message : messages) {
						int senderId = message.getSender(); // 发送人
						if(senderId == sender){ // 如果最后一条消息的发送人是自己，则设置为已读状态
							message.setStatus(1);
						}
						if(message.getCid()==chatLogs.getCid()){
							chatLogEntity.setContent(message.getContent()); // 设置内容
							chatLogEntity.setStatus(message.getStatus()); // 消息状态
							
							String dateTime =message.getDateTime();
							String dateArr[] = dateTime.split("\\s");
							chatLogEntity.setDateTime(CalendarUtil.dealDate(dateArr[0], dateArr[1]));
						}
					}
					messageMap = new HashMap<String, Object>();
					messageMap.put("content", chatLogEntity.getContent());
					messageMap.put("dateTime", chatLogEntity.getDateTime());
					messageMap.put("headUrl", ReadPropertiesUtil.getIMGREAD(chatLogEntity.getHeadUrl()+""));
					messageMap.put("nickName", chatLogEntity.getNickName());
					messageMap.put("oppositer", chatLogEntity.getOppositer());
					messageMap.put("status", chatLogEntity.getStatus());
					resultMap.add(messageMap);
					//chatEntitys.add(chatLogEntity); // 加到泛型集合
				}
			}
			
			/*for (ChatLogEntity chat : chatEntitys) {
				Map<String, Object> messageMap = new HashMap<String, Object>();
				messageMap.put("content", chat.getContent());
				messageMap.put("dateTime", chat.getDateTime());
				messageMap.put("headUrl", ReadPropertiesUtil.getIMGREAD(chat.getHeadUrl()+""));
				messageMap.put("nickName", chat.getNickName());
				messageMap.put("oppositer", chat.getOppositer());
				messageMap.put("status", chat.getStatus());
				resultMap.add(messageMap);
			}*/
			
			map.remove("list");
			map.remove("repiList");
			
			map.put("code", 1);
			map.put("message", resultMap);
			return "succ";
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 0);
			map.put("msg", "系统异常");
			return "succ";
		}
	}
	
	/**
	 * 删除聊天消息列表
	 * @return
	 */
	@Action(value="delmessagelist",results={@Result(name="succ",type="json",params={"root","map"})})
	public String delMessageList() {
		map = new HashMap<String, Object>();
		try {
			int idongId = chatLog.getIdongId();
			int oppositer = chatLog.getOppositer();
			if(idongId > 0 && oppositer > 0){
				
				Map<String, Object> paraMap = new HashMap<String, Object>();
				paraMap.put("idongId", idongId);
				paraMap.put("oppositer", oppositer);
				chatLogBiz.getMessageChat(paraMap);
				
				map.put("code", 1);
				map.put("result", "删除成功");
				return "succ";
			}else{
				map.put("code", 0);
				map.put("msg", "参数缺失");
				return "succ";
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 0);
			map.put("msg", "系统异常");
			return "succ";
		}
	}
	
	/**
	 * 删除单条聊天记录
	 * @return
	 */
	@Action(value="deloneletter",results={@Result(name="succ",type="json",params={"root","map"})})
	public String delOneLetter() {
		map = new HashMap<String, Object>();
		try {
			int infoId = chatLog.getInfoId();
			int idongId = chatLog.getIdongId();
			if(infoId > 0 && idongId > 0){
				
				Map<String, Object> paraMap = new HashMap<String, Object>();
				paraMap.put("idongId", idongId);
				paraMap.put("infoId", infoId);
				chatLogBiz.delOneLetter(paraMap);
				
				map.put("code", 1);
				map.put("result", "删除成功");
				return "succ";
			}else{
				map.put("code", 0);
				map.put("msg", "参数缺失");
				return "succ";
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 0);
			map.put("msg", "系统异常");
			return "succ";
		}
	}
}
